package dog

import (
	"sync"
	"errors"
	"fmt"
)

type DogKeeper struct {
	dog_map   map[int]IDog
	lastDogId int

	mutex sync.Mutex
}

func NewDogKeeper() *DogKeeper {
	return &DogKeeper{
		dog_map:   make(map[int]IDog),
		lastDogId: 0,
		mutex:     sync.Mutex{},
	}
}

func (this *DogKeeper) Serialize() {

}

func (this *DogKeeper) DeSerialize() {

}

func (this *DogKeeper) GetAllDog() []IDog {
	var dogs []IDog

	for _, v := range this.dog_map {
		dogs = append(dogs, v)
	}

	return dogs
}

func (this *DogKeeper) getNextDogId() int {
	this.mutex.Lock()
	defer this.mutex.Unlock()

	this.lastDogId++
	return this.lastDogId
}

func (this *DogKeeper) FosterageADog(dog IDog) (dog_id int, err error) {
	if dog.GetDogId() != 0 {
		err = errors.New("this dog has been fosterage.")
		return
	}

	dog_id = this.getNextDogId()
	dog.setDogId(dog_id)
	this.dog_map[dog_id] = dog
	
	go this.monitoringdog(dog)
	
	return
}

func (this *DogKeeper)monitoringdog(dog IDog)  {
	for !dog.IsDied(){
		dog.SpendLife()
	}

	delete(this.dog_map, dog.GetDogId())

	fmt.Println("Go die ", dog)
}

func (this *DogKeeper) FindDog(id int) IDog {
	return this.dog_map[id]
}
